package cn.edu.jxau.controller;

import java.io.IOException;
import java.util.Random;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;

public class SendCodeToMailServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");


    	response.sendRedirect("text/html;charset=utf-8");
    	/*HttpSession session=request.getSession();
    	String mailnum=(String) session.getAttribute("mail");*/
    	

    	

    	//生成四位数的随机验证码
	    StringBuffer code = new StringBuffer();  
        String sourceStr = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";      
        Random random = new Random();  
        for(int i=0; i<4; i++)  
         {  
            code.append(sourceStr.charAt(random.nextInt(30))+"");  
         }  
        String m=code.toString();
	    Cookie cookie=new Cookie("code",m);
	    cookie.setMaxAge(60*5);
	    response.addCookie(cookie);

    	response.setContentType("text/html;charset=utf-8");
    	HttpSession session=request.getSession();
    	String mailnum=(String) session.getAttribute("mail");
    	System.out.println(mailnum);
    	Mail mail = new Mail("17779144758@163.com", mailnum);  //向目标邮箱发送验证码

		

		mail.setContent(m);

		mail.setSubject("【驴友网】修改密码");
		mail.setContent(m+"(动态验证码),请在五分钟内填写");


		Session sessionmail = MailUtils.createSession("smtp.163.com", "17779144758", "wanxintao123");
		try {
			MailUtils.send(sessionmail, mail);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.getWriter().print("");
	}

}
